package com.storage.system.service.impl;

import com.storage.system.service.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * redis 服务
 *
 * @author wb-zh270168
 */
@Service
public class RedisService implements IRedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void setKey(String key, String value) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        //15分钟过期
        ops.set(key, value, 300, TimeUnit.SECONDS);
    }

    /**
     *
     * @Title: set
     * @Description: TODO 字符串存入值
     * @param: @param key
     * @param: @param value
     * @param: @param expire  过期时间   （毫秒）
     * @return: void
     * @throws
     */
    @Override
    public void setKey(String key, String value,Long expire){
        redisTemplate.opsForValue().set(key,value, expire,TimeUnit.MILLISECONDS);
    }

    /**
     *
     * @Title: hasKey
     * @Description: TODO 判断key下是否有值
     * @param: @param key 判断的key
     * @param: @return
     * @return: Boolean
     * @throws
     */
    @Override
    public Boolean hasKey(String key) {
        try {
            return redisTemplate.opsForHash().getOperations().hasKey(key);
        }finally {
            //手动释放资源
            RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
        }
    }

    @Override
    public String getValue(String key) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        return ops.get(key);
    }

    @Override
    public void delete(String key) {
        redisTemplate.delete(key);
    }

}